package thread.chapter02;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author xinya
 * @version 1.0
 * @project javacore
 * @description unsafe测试
 * @date 2023/12/12 18:10:36
 */
public class TestUnsafe {
    static  Unsafe unsafe;

    static  long stateOffset;

    private volatile  long state;

    static {
        try {
            // 反射获取unsafe成员变量
            Field field= Unsafe.class.getDeclaredField("theUnsafe");

            field.setAccessible(true);

            unsafe = (Unsafe) field.get(null);

            stateOffset = unsafe.objectFieldOffset(TestUnsafe.class.getDeclaredField("state"));


        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        TestUnsafe testUnsafe = new TestUnsafe();
        System.out.println(unsafe.getInt(testUnsafe, stateOffset));
        Boolean success = unsafe.compareAndSwapInt(testUnsafe, stateOffset, 0, 1);
        System.out.println(success);
        System.out.println(unsafe.getInt(testUnsafe, stateOffset));
    }

}
